# -*- coding: utf-8 -*-
"""
Created on Fri Sep  9 17:18:10 2022

@author: Ewing
"""

import configparser
import logging
import logging.handlers
import sys
from openpyxl import load_workbook
from openpyxl.styles import PatternFill, Alignment, Side, Border
import os
from PyQt5.QtWidgets import QWidget, QVBoxLayout, QPushButton, QMessageBox, QApplication, QLabel


def run():
    if len(sys.argv) > 1:
        config_file_path = sys.argv[1]
    else:
        config_file_path = "config.ini"
    # config_file_path=r"C:\Users\pengzhongqi\Desktop\脚本\MiniTools\zengwei\4\config.ini"
    config = configparser.ConfigParser()
    config.read(config_file_path, encoding='utf-8')
    tablepath = config.get("splittable", "tablepath")
    colname = config.get("splittable", "colname")
    print("正在读取配置文件....")
    print("扫描文件:" + tablepath)
    print("拆表字段:" + colname)
    print("正在执行脚本-4.表格拆分")

    import pandas as pd
    # 1、读取原Excel文件
    data = pd.read_excel(tablepath)
    # 2、取出去重后的条件列表,只会识别出最新创建的工作表，建议汇总工作薄中只保留一份工作表。
    class_list = list(data[colname].unique())
    print(class_list)
    # 3、通过for循环 + 布尔值让系统自动筛选同名行，并进行保存！
    for i in class_list:
        data_cut = data[data[colname] == i]
        data_cut.to_excel(r'.\%s.xlsx' % (i))

    # 返回当前目录下所有文件名
    filepath = r".\\"
    files = os.listdir(filepath)
    # 循环文件名列表
    for file in files:
        # 拼接文件路径
        if ".xlsx" not in file:
            continue
        file_path = filepath + file
        print(file)
        # 打开工作簿
        wb = load_workbook(file_path)
        # 打开工作表
        ws = wb.active

        # 调整列宽
        ws.column_dimensions['A'].width = 10
        ws.column_dimensions['B'].width = 10
        ws.column_dimensions['C'].width = 10
        ws.column_dimensions['D'].width = 10

        # 定义单元格样式
        '''
        #定义表头颜色为橙色
        header_fill=PatternFill('solid',fgColor='FF7F24')
            #定义表中颜色为浅黄色
        content_fill=PatternFill('solid',fgColor='FFFFE0')
            #定义表尾颜色为淡橘红色
        bottom_fill=PatternFill('solid',fgColor='EE9572')
        '''
        # 定义对其方式，纵向居中，横向居中
        align = Alignment(horizontal='center', vertical='center')

        # 定义边样式为细条
        side = Side('thin')
        # 定义表头边框样式有底边、右边
        head_border = Border(bottom=side, right=side)
        # 定义表中边框样式有左边
        content_border = Border(bottom=side, right=side, left=side, top=side)

        column = ws['A']
        mylist = [column[x].value for x in range(len(column))]

        i = 0
        for cell in column:
            cell.value = i
            i = i + 1
        # 取出第一行单元格
        for cell in ws[1]:
            # 设置单元格填充颜色
            # cell.fill=header_fill
            # 设置单元格对其方式
            cell.alignment = align
            # 设置单元格边框
            cell.border = head_border

        # 取出表中的各行,第二行到倒数第二行
        for row in ws.iter_rows(min_row=2, max_row=ws.max_row):
            for cell in row:
                # cell.fill=content_fill
                cell.alignment = align
                cell.border = content_border

        wb.save(file_path)

    print("Split_Table.py : The job has been done successfully")
    return True


class win(QWidget):
    def __init__(self):
        super().__init__()
        self.setFixedWidth(180)
        self.setWindowTitle(" ")

        layout = QVBoxLayout()
        openConfig = QPushButton("打开配置", self)
        # openConfig.setText()
        # openTemplate = QPushButton("打开配置模板", self)
        # openTemplate.setText()
        startButton = QPushButton("运行", self)

        layout.addWidget(QLabel("表格拆分"))
        # layout.addWidget(QLabel("文件"))
        layout.addWidget(openConfig)
        # layout.addWidget(openTemplate)
        # layout.addStretch()
        layout.addWidget(startButton)

        self.setLayout(layout)
        openConfig.clicked.connect(self.openConfig)
        # openTemplate.clicked.connect(self.openTemplate)
        startButton.clicked.connect(self.start)

    def openConfig(self):
        if len(sys.argv) > 1:
            config_file_path = sys.argv[1]
        else:
            config_file_path = "config.ini"
        print(config_file_path)
        # print(len(sys.argv))
        os.system(config_file_path)
        pass

    def start(self):
        try:
            res = run()
        except Exception as e:
            print(repr(e))
            res = False

        if res:
            QMessageBox.information(self, "", "处理成功！")
        else:
            QMessageBox.critical(self, "", "处理失败，请查看后台日志！")


if __name__ == '__main__':
    app = QApplication(sys.argv)
    main = win()
    main.show()
    sys.exit(app.exec())
